#include "MyNet.h"
#include <stdio.h>
using std::string;
class Mail {
    char userName[100];
    char passWord[100];
    char sendAddr[100];
    char acceptAddr[100];
    char buf[1024];
    string sbuf;
    rio_t rio;
    int fd, n;

    public:
    Mail(char* hostname, int port) {
        fd = open_clientfd(hostname, port);
        rio_readinitb(&rio, fd);
        rio_readlineb(&rio, buf, 1024);
        printf("%s", buf);
    }
    ~Mail() { close(fd); }
    void sendMailByServer(string username, string passwd, string sendaddr, string acceptaddr, string contents) {
        sprintf(userName, "%s\r\n", username.data());
        sprintf(passWord, "%s\r\n", passwd.data());
        sprintf(sendAddr, "mail from:<%s>\r\n", sendaddr.data());
        sprintf(acceptAddr, "rcpt to:<%s>\r\n", acceptaddr.data());
        sbuf = "HELO localhost\r\n";
        rio_writen(fd, (char*)sbuf.data(), sbuf.length());
        rio_readlineb(&rio, buf, 1024);
        printf("%s", buf);

        sbuf = "AUTH LOGIN\r\n";
        rio_writen(fd, (char*)sbuf.data(), sbuf.length());
        rio_readlineb(&rio, buf, 1024);
        printf("%s", buf);

        rio_writen(fd, (char*)userName, strlen(userName));
        rio_readlineb(&rio, buf, 1024);
        printf("%s", buf);

        rio_writen(fd, (char*)passWord, strlen(passWord));
        rio_readlineb(&rio, buf, 1024);
        printf("%s", buf);
        sleep(1);

        rio_writen(fd, (char*)sendAddr, strlen(sendAddr));
        rio_readlineb(&rio, buf, 1024);
        printf("%s", buf);

        rio_writen(fd, (char*)acceptAddr, strlen(acceptAddr));
        rio_readlineb(&rio, buf, 1024);
        printf("%s", buf);

        sbuf = "DATA\r\n";
        rio_writen(fd, (char*)sbuf.data(), sbuf.length());
        rio_readlineb(&rio, buf, 1024);
        printf("%s", buf);

        rio_writen(fd, (char*)contents.data(), contents.length());
        rio_readlineb(&rio, buf, 1024);
        printf("%s", buf);

       // sbuf = "\r\n.\r\n";
       // rio_writen(fd, (char*)sbuf.data(), sbuf.length());
       // rio_readlineb(&rio, buf, 1024);
       // printf("%s", buf);

        sbuf = "QUIT\r\n";
        rio_writen(fd, (char*)sbuf.data(), sbuf.length());
        rio_readlineb(&rio, buf, 1024);
        printf("%s", buf);

    }

    void sendLocalMail(string sendaddr, string acceptaddr, string contents) {

    }
};
int main(int argc, char** argv) {
    Mail mail((char*)"smtp.163.com", 25);
    string f = "From: lixiaobai0922@163.com\r\n";
    string t = "To: 1106419857@qq.com\r\n";
    string sub = "Subject: 验证码\r\n\r\n";
    string body = "FDKSH324fk\r\n";
    string en = "\r\n.\r\n";
    string contents = t + f + sub + body + en;
    mail.sendMailByServer("bGl4aWFvYmFpMDkyMg==", "MXFhejJ3c3g=", "lixiaobai0922@163.com", "1106419857@qq.com", contents);
    return 0;
}
